<template>
  <article class="page">
    <headerbar>发布视频</headerbar>
    <section class="frame-content-sub bg-default">
      <section class="inner-content pdv-9 pdh-4">
        <div class="input-row-wrap">
          <div class="name">视频标题：</div>
          <input v-model="form.title" type="text" placeholder="请填写标题" />
        </div>
        <div class="input-row-wrap" v-if="!hasDgwGroup">
          <div class="name">关联党工委：</div>
          <cube-select v-model="form.dgwId" :options="dgwOptions"></cube-select>
        </div>
        <div class="input-row-wrap" v-show="hdfqOptions.length>0">
          <div class="name">活动分区：</div>
          <!-- <cube-select v-model="form.checkedActivity" :options="hdfqOptions"></cube-select> -->
          <cube-checkbox-group v-model="form.checkedActivity" :options="hdfqOptions" :horizontal="false" shape="square" :hollow-style="false"></cube-checkbox-group>
        </div>

        <div class="input-row-wrap">
          <div class="name">视频封面（如未上传封面图片，则默认视频第一帧为封面）：</div>
          <!--<div class="cover">
            <img :src="posterCover" alt="">
          </div>-->
          <section class="upload-wrap">
            <cube-upload
              ref="uploadPoster"
              action=""
              accept="image/*"
              :simultaneous-uploads="1"
              @files-added="addPoster"
              @file-removed="removePoster"
              :max="1"
            />
          </section>
        </div>

        <div class="input-row-wrap input-row-wrap-sp" v-if="imageFiles.length === 0">
          <div class="name">视频：</div>
          <section class="upload-wrap">
            <cube-upload
              ref="upload1"
              action=""
              accept="video/*"
              :simultaneous-uploads="1"
              @files-added="addFile"
              @file-removed="removeFile"
              :max="1"
              v-model="videoFiles"
            />
          </section>
        </div>

        <div class="input-row-wrap input-row-wrap-sp" v-if="imageFiles.length > 0">
          <div class="name">视频：</div>
          <section class="upload-wrap">
            <cube-upload
              ref="upload"
              action=""
              accept="image/*"
              :simultaneous-uploads="1"
              v-model="imageFiles"
              @file-removed="removeImage"
              :max="1"
            />
          </section>
        </div>

        <videoCoverComponent
          @onCover="onCover"
          :url="videoUrl"
        ></videoCoverComponent>

        <div class="block pdh-4 pdv-4 long-tip">
          <div class="">
            温馨提示：“红云播客”社区主要用于展示党组织和党员创作的党建宣传及党员教育短视频，请勿上传与上述内容无关的作品。
          </div>
        </div>
        <p class="pdv-2"></p>

        <div @click="save()" class="default-block-btn">提交作品</div>

        <div class="pdv-5"></div>
        <aliUpload ref="uploader" @onSuccess="onVideoUploaded"></aliUpload>
      </section>
    </section>
  </article>
</template>

<script>
import tools from "@/utils/tools";
import api from "@/common/config/api";
import videoCoverComponent from "@/components/common/videoCoverComponent.vue";
import _ from "lodash";
import aliUpload from "@/components/common/AliUpload.vue";
import { ossUpload } from "@/utils/aliyun_oss";
import uuidv1 from "uuid/v1";
import $ from "../../../../../static/js/jquery-1.12.4.min";
export default {
  components: { videoCoverComponent, aliUpload },
  name: "demandSurveyFeedback",
  data() {
    return {
      channelId: "19a64c36d6ff4442948bb99bb1a06e77",
      form: {
        title: "",
        dgwId: '',
        checkedActivity: [],
        content: "",
        files: "",
      },
      dgwOptions: [],
      hdfqOptions: [],
      posterCover: "",
      videoUrl: "",
      videoCoverWellBeUpload: "",
      videoSelected: null,
      videoWellBeUpload: "",
      posterList: [],
      videoList: [],
      videoFiles: [],
      imageFiles: [],
      hasIgnore: false,
      hasDgwGroup: true, //默认关联了党工委
      loading: false,
      tjzpDisabled: false, //防止提交作品重复提交
    };
  },
  created() {
    let me = this
    window.onBack = function () {
      me.giveUpUploadDialog(function () {
        me.tools.back()
      })
    }
    this.getActivityList();
    if (this.$store.state.userInfo.dgwGroupId) {
      this.hasDgwGroup = true;
    } else {
      this.hasDgwGroup = false;
      this.getRegionalList();
    }
  },
  methods: {
    // 获取活动列表
    getActivityList() {
      let data = {
        name: "",
        pageNo: 1,
        pageSize: 20,
        status: ''
      };
      this.fetchService.play_activityPage(data).then((res) => {
        if (res.code !== 0) {
          return this.tools.tip(res.message);
        }
        var arr = [];
        res.data.forEach(item => {
          var obj = {
            label: item.name,
            value: item.id
          }
          arr.push(obj);
        });
        this.hdfqOptions = arr;
      });
    },
    // 获取区域数据
    getRegionalList() {
      let data = {
      };
      return this.fetchService.play_queryShowInAdd(data).then((res) => {
        if (res.code !== 0) {
          return this.tools.tip(res.message || '接口服务出错，请联系管理员')
        }
        var arr = [];
        res.data.forEach(item => {
          var obj = {
            text: item.name,
            value: item.code
          }
          arr.push(obj);
        });
        this.dgwOptions = arr;
      });
    },
    uploadPoster(file) {
      let formData = new FormData();
      formData.append("file", file[0]);
      return this.fetchService.o_upload(formData).then((res) => {
        if (res.code !== 0) {
          return tools.tip(res.message);
        }
        let ret = res.data;
        this.posterList.push(ret);
        return ret;
      });
    },
    addPoster(file) {
      console.log(this.$refs.uploadPoster);
      console.log("addPoster", file[0]);
      this.videoCoverWellBeUpload = file[0];
    },
    removePoster(file) {
      this.videoCoverWellBeUpload = "";
    },
    addFile(file) {
      this.hasIgnore = false;
      var size = Array.prototype.slice.call(file, 0)[0].size;
      console.log("size", size);
      var isLt50M = size / 1024 / 1024 < 50;
      console.log('this.videoFiles',this.videoFiles)
      if (!isLt50M) {
        this.$refs.upload1.$forceUpdate();
        file.ignore = true
        this.hasIgnore = true;
        this.videoFiles = [];
        tools.tip("上传的视频文件大小超过最大值50MB，请重新上传！");
        return false;
      }else{
        this.hasIgnore = false;
      }

      this.videoSelected = file;
      this.videoWellBeUpload = Array.prototype.slice.call(file, 0);
      this.videoUrl = window.URL.createObjectURL(file[0]);
      //        // 通过阿里SDK上传视频
      //        console.log(file[0])
      //        this.$refs.uploader.fileChange(file[0])
      //        this.$refs.uploader.authUpload()
    },
    removeFile(file) {
      this.hasIgnore = false;
      this.videoSelected = null;
      this.videoWellBeUpload = "";
      this.videoUrl = "";
    },
    uploadVideo(file) {
      if (this.posterList.length > 0) {
        this.imageFiles[0] = this.posterList[0];
      }
      let uploadFile = file[0];
      let formData = new FormData();
      formData.append("file", uploadFile);
      this.tools.showLoading("视频上传中...");
      return this.fetchService.o_upload(formData).then((res) => {
        this.tools.hideLoading();
        if (res.code !== 0) {
          return this.tools.tip(res.message);
        }
        this.tools.tip("上传成功");
        let ret = res.data;
        this.videoList.push({
          fileId: res.data.fileId,
          fileName: uploadFile.name,
          totalBytes: res.data.totalBytes,
          path: ret.path,
        });
        return ret;
      });
    },
    onCover(file, image) {
      if (this.videoCoverWellBeUpload) {
        this.$refs.upload1.files = [{ file, base64: image }];
        return window.URL.revokeObjectURL(this.videoUrl);
      }
      this.videoCoverWellBeUpload = file;
      // this.posterCover = image;
      this.$refs.upload1.files = [{ file, base64: image }];
      this.$refs.uploadPoster.files = [{ file, base64: image }];
      window.URL.revokeObjectURL(this.videoUrl);
    },
    videoPic() {
      if (this.posterList.length > 0) {
        return this.posterList[0].fileId;
      }
      return "";
    },
    saveVideoInfo(files, listpic, listPicUrl) {
      /* if (this.posterList.length <= 0) {
          return tools.tip('请选择视频')
        }*/
      /*if (this.videoFiles.length <= 0) {
          return tools.tip('请上传视')
        }*/
      let params = {
        channelId: this.channelId,
        comments: 0,
        downs: 0,
        ups: 0,
        source: "筑红云APP",
        checkStatus: 0,
        status: 2,
        views: 0,
        listPic: listpic || this.videoPic(),
        listPicUrl: listPicUrl || '',
        sortNum: 0,
        contents: this.form.title,
        isTop: 0,
        files: files,
        title: this.form.title,
        dgwId: this.hasDgwGroup ? '' : this.form.dgwId,
        checkedActivity: this.form.checkedActivity
      };
      if (this.TYPE === "ALI") {
        params.transcodeStatus = 0;
      }
      this.tools.showLoading("发布中...");
      this.fetchService.addOrUpdate(params).then((res) => {
        this.tools.hideLoading();
        this.loading = false
        if (res.code !== 0) {
          return this.tools.tip(res.message || "操作失败");
        }
        this.tools.tip("上传成功、等待人工审核！");
        setTimeout(() => {
          this.tools.back();
        }, 3000);
      });
    },
    // 当视频上传完成
    async onVideoUploaded(videoData) {
      console.log("当视频上传完成", videoData);
      let uploadData = await ossUpload(this.videoCoverWellBeUpload);
      let fileId = uuidv1().replace(/-/g, "");
      let addFileData = await this.addFileCenter(
        "OSS",
        fileId,
        uploadData.fileUrl
      );
      let listpic = addFileData.fileId;
      let listPicUrl = addFileData.desc;
      console.log("listpic", listpic);
      this.tools.hideLoading();
      this.saveVideoInfo(
        [
          {
            fileId: videoData.videoId,
            fileName: videoData.file.name,
            totalBytes: videoData.file.size,
            path: videoData.object,
          },
        ],
        listpic,
        listPicUrl
      );
    },
    // OSS
    ossSave() {
      this.tools.showLoading("上传视频...");
      // 通过阿里SDK上传视频
      console.log(this.videoWellBeUpload);
      console.log(this.videoSelected);
      this.$refs.uploader.fileChange(this.videoWellBeUpload[0]);
      this.$refs.uploader.authUpload();
    },
    save() {
      if (this.form.title === "") {
        return tools.tip("请填写标题");
      }
      if (!this.hasDgwGroup && this.form.dgwId === '') {
        return tools.tip("请选择党工委");
      }
      if (this.videoCoverWellBeUpload === "") {
        return tools.tip("请选择封面");
      }
      if (this.hasIgnore) {
        return tools.tip("上传的视频文件大小超过最大值50MB，请重新上传！");
      }
      if (this.videoWellBeUpload === "") {
        return tools.tip("请选择视频");
      }
      if (this.tjzpDisabled) {
        return;
      }
      this.tjzpDisabled = true;
      setTimeout(() => {
          this.tjzpDisabled = false;
      }, 2000);
      this.loading = true
      if (this.TYPE === "ALI") {
        return this.ossSave();
      }
      this.uploadPoster([this.videoCoverWellBeUpload]).then((res) => {
        console.log(this.tools.getImgUrl(res.fileId));
        console.log(this);
        console.log(this.videoWellBeUpload);
        this.uploadVideo(this.videoWellBeUpload).then((data) => {
          this.saveVideoInfo(this.videoList);
        });
      });
    },
    removeImage(file) {
      this.videoFiles = [];
    },
    // 文件添加到文件中心 fileSystem:OSS  VOD
    // OSS https://laminae-oss.oss-cn-chengdu.aliyuncs.com/用户ID
    async addFileCenter(fileSystem = "OSS", fileId, fileUrl) {
      let coverStatus = "1";
      let params = {
        fileSystem,
        coverStatus,
        fileId,
        fileName: fileId,
      };
      if (fileSystem === "OSS") {
        params.desc = fileUrl;
      }
      const result = await new Promise((resolve, reject) => {
        this.fetchService
          .sysFileSave(params)
          .then((res) => {
            console.log("保存附件：", res);
            if (res.code === 0) {
              resolve(res.data);
            } else {
              reject({});
            }
          })
          .catch((e) => {
            reject({});
          });
      });
      console.log(result);
      return result;
    },
    giveUpUploadDialog (next) {
      if (!this.loading) {
        window.onBack = null
        this.tools.back()
        return false
      }
      this.tools.hideLoading()
      let _this = this
      this.dialog = this.$createDialog({
        type: 'confirm',
        icon: '',
        title: '温馨提示',
        content: '确认放弃上传吗？',
        confirmBtn: {
          text: '确定',
          active: true,
          disabled: false,
          href: 'javascript:;'
        },
        cancelBtn: {
          text: '取消',
          active: false,
          disabled: false,
          href: 'javascript:;'
        },
        onConfirm: () => {
          _this.sureBack(next)
        },
        onCancel: () => {
          _this.tools.showLoading('上传视频...')
        }
      }).show()
    },
    sureBack (next) {
      window.onBack = null
      // 停止接口提交
      this.$refs.uploader.pauseUpload()
      this.loading = false
      next()
    },
    globleBack () {
      let me = this
      this.giveUpUploadDialog(function () {
        me.tools.back()
      })
    }
  },
  beforeRouteLeave (to, from, next) {
    window.onBack = null
    next()
  }
};
</script>

<style scoped lang="scss">
.cover {
  img {
    width: auto;
    height: 300px;
  }
}
.input-row-wrap .cube-select-placeholder {
  font-size: 14PX;
}
</style>
